# -*- encoding: utf-8 -*-

import pymysql
from dbutils.simple_pooled_db import PooledDB
from datascrapy.settings import MYSQL_HOST
from datascrapy.settings import MYSQL_PORT
from datascrapy.settings import MYSQL_USER
from datascrapy.settings import MYSQL_PASS
from datascrapy.settings import MYSQL_DB
from datascrapy.settings import MYSQL_CON_NUM

global local_pool

# MySQL相关设置
local_pool = PooledDB(pymysql, MYSQL_CON_NUM, host=MYSQL_HOST, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_DB,
                     port=MYSQL_PORT, cursorclass=pymysql.cursors.DictCursor)


class DbConnect(object):
    def __init__(self):
        self.dict_conn = local_pool.connection()
        self.dict_cursor = self.dict_conn.cursor()

    def execute(self, sql, param):
        self.dict_cursor.execute(sql, param)

    def execute_without_param(self, sql):
        self.dict_cursor.execute(sql)

    def execute_and_fetch(self, sql, param):
        self.dict_cursor.execute(sql, param)
        return self.dict_cursor.fetchall()

    def commit_connect(self):
        self.dict_conn.commit()
        self.dict_cursor.close()
        self.dict_conn.close()
